const COS = require('cos-nodejs-sdk-v5')
const AESUtils = require('./aes').default
const axios = require('axios')

const COS_PATH = '/static/icon/sms/'

exports.uploadFile = async (fileName, file) => {
  //
  await generateTmpToken()

  //
  const cos = new COS({
    getAuthorization: (options, callback) => {
      callback({
        TmpSecretId: process.env.tmpSecretId,
        TmpSecretKey: process.env.tmpSecretKey,
        SecurityToken: process.env.sessionToken,
        ExpiredTime: process.env.expiredTime,
      })
    },
  })

  // 上传图片
  cos.putObject(
    {
      Bucket: process.env.bucket,
      Region: process.env.region,
      Key: `${COS_PATH}${fileName}`,
      Body: file, // 本地文件路径
    },
    (err, data) => {
      if (err) {
        console.error('err', err)
      } else {
        console.log('data', data)
      }
    }
  )
}

async function generateTmpToken() {
  // 失效过期
  if (
    !process.env.tmpSecretId ||
    process.env.expiredTime * 1000 <= new Date().getTime()
  ) {
    const cosToken = await reFindCosTmpToken()

    process.env.tmpSecretId = cosToken.tmpSecretId
    process.env.tmpSecretKey = cosToken.tmpSecretKey
    process.env.sessionToken = cosToken.sessionToken
    process.env.expiredTime = cosToken.expiredTime
  }
}

async function reFindCosTmpToken() {
  const requestConfig = {
    url: `http://www.weixiaotong.com.cn/api/pc/base_cosclient_getCosToken`,
    data: {
      params: {
        requestUrl:
          'http://www.weixiaotong.com.cn/weixt/portal/#/main/microportal/newsedit/3/0/0/2289?title=',
        bucket: 'weixt-static-1305346148',
        isEncrypt: true,
        token: '2056409ead6bfc2b787c5a470dd7e9bf',
      },
    },
    method: 'POST',
    headers: { 'Content-Type': 'application/json; charset=UTF-8' },
  }
  const res = await axios(requestConfig).then((res) => res.data)

  return {
    ...cosDecrypt(res.data.credentials),
    expiredTime: res.data.expiredTime,
  }
}

function cosDecrypt(data) {
  // cos 需要解密项
  const cosDecryptKeys = ['tmpSecretId', 'sessionToken', 'tmpSecretKey']

  cosDecryptKeys.forEach((key) => {
    data[key] = AESUtils.decrypt(data[key], {
      mode: 'ECB',
    })
  })

  return data
}
